package com.atguigu.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.pojo.Permission;
import com.atguigu.pojo.Role;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
//bean对象的id就是SpringSecurityUserService的首字母小写及id=springSecurityUserService
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference //注意：此处要通过dubbo远程调用用户服务
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名称查询用户对象,并且查询关联角色以及关联权限(与套餐详情页面类似)
        User user = userService.findUserByUsername(username);
        //2.构建权限结合  SimpleGrantedAuthority实现了GrantedAuthority
        Set<GrantedAuthority> authorities =new HashSet<GrantedAuthority>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));//用角色表示权限时,角色名称增加前缀:Role
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //3.返回用户对象
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);

    }
}
